package com.nbicc.file.service.impl;

import com.nbicc.common.sequence.Sequence;
import com.nbicc.common.utils.RandomAccessFileUtil;
import com.nbicc.file.po.File;
import com.nbicc.file.bo.FileDesc;
import com.nbicc.file.mapper.FileMapper;
import com.nbicc.file.service.IFileService;
import com.nbicc.file.utils.FileUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Date;

@Service("FileServiceImpl")
public class FileServiceImpl implements IFileService{

    @Autowired
    private Sequence sequence;
    @Autowired
    private FileUtils fileUtils;
    @Autowired
    private FileMapper fileMapper;

    @Override
    public void uploadFile(FileDesc fileDesc, InputStream input) throws IOException{
        if(fileDesc.getId() == null){
            fileDesc.setId(sequence.nextId());
        }
        RandomAccessFileUtil.write(fileUtils.rootPath()+fileDesc.getRelativePath(),
                fileDesc.getPos(),
                fileDesc.getLength(),
                input);
        loadFileDesc(fileDesc);
    }

    @Override
    public void downloadFile(FileDesc fileDesc, OutputStream output) throws IOException {
        RandomAccessFileUtil.read(fileUtils.rootPath()+fileDesc.getRelativePath(),
                fileDesc.getPos(),
                fileDesc.getLength(),
                output);
    }

    @Override
    public void deleteFile(Number id) throws IOException {
        File file = fileMapper.selectById(id);
        if(file == null){
            throw new IOException("文件不存在");
        }else{
            FileDesc fileDesc = new FileDesc();
            BeanUtils.copyProperties(file,fileDesc);
            java.io.File f = new java.io.File(fileUtils.rootPath()+fileDesc.getRelativePath());
            if(f.exists()){
                f.delete();
            }
            fileMapper.deleteById(id);
        }
    }

    /**
     * 记录文件上传信息
     * @param fileDesc
     */
    @Transactional
    public void loadFileDesc(FileDesc fileDesc){
        File file = fileMapper.selectById(fileDesc.getId());
        if(file == null){
            file = new File();
            BeanUtils.copyProperties(fileDesc,file);
            file.setCreateTime(new Date());
            file.setModifyTime(file.getCreateTime());
            fileMapper.insert(file);
        }else{
            BeanUtils.copyProperties(fileDesc,file);
            file.setModifyTime(new Date());
            fileMapper.updateById(file);
        }
    }

    public FileDesc uploadFile(HttpServletRequest request , MultipartFile uploadFile) throws IOException{
        FileDesc fileDesc = queryUploadFileDesc(request , uploadFile);
        uploadFile(fileDesc,uploadFile.getInputStream());
        return fileDesc;
    }

    public void downloadFile(HttpServletRequest request, HttpServletResponse response, long id) throws  IOException{
        FileDesc fileDesc = queryDownloadFileDesc(id,request);
        response.setHeader("Content-Disposition", "attachment;filename="+new String(fileDesc.getName().getBytes("utf-8"),"iso8859-1"));
        downloadFile(fileDesc,response.getOutputStream());
    }

    public FileDesc queryDownloadFileDesc(long id , HttpServletRequest request){
        FileDesc fileDesc = new FileDesc();
        fileUtils.iniSegment(fileDesc , request);
        File file = fileMapper.selectById(id);
        if(file == null){
            return null;
        }
        BeanUtils.copyProperties(file , fileDesc);
        return fileDesc;
    }

    @Override
    public FileDesc queryUploadFileDesc(HttpServletRequest request , MultipartFile uploadFile) {
        FileDesc fileDesc = new FileDesc();
        fileUtils.iniSegment(fileDesc , request);
        if(fileDesc.isSegment()){           //如果是续传  则文件名就为原id
            File file = fileMapper.selectById(Long.valueOf(uploadFile.getOriginalFilename()));
            fileDesc.setId(file.getId());
            fileDesc.setName(file.getName());
            fileDesc.setRelativeFolder(file.getRelativeFolder());
            fileDesc.addSize(uploadFile.getSize());
        }else{
            fileDesc.setName(uploadFile.getOriginalFilename());
            fileDesc.setRelativeFolder(fileUtils.relativeFolder());
            fileDesc.setSize(uploadFile.getSize());
        }
        return fileDesc;
    }

}
